//
//  SinaHomePictureView.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/17.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit

class SinaHomePictureView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate {

    let picCellID = "picCellID"
    
    var pictureInfoModelList: [SinaPictureInfoModel]?{
        didSet{
            self.reloadData()
        }
    }

    override func awakeFromNib() {
        
        super.awakeFromNib()
        self.dataSource = self
        self.delegate = self
        //注册单元格
        let nib = UINib(nibName: "SinaHomePictureViewCell", bundle: nil)
        self.register(nib, forCellWithReuseIdentifier: picCellID)
        
    }
    
    // MARK:
    // MARK: - 数据源代理
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfoModelList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picCellID, for: indexPath) as! SinaHomePictureViewCell
        cell.pictureInfoModel = pictureInfoModelList?[indexPath.item]
        return cell
    }
    
    
    // MARK:
    // MARK: - 被选择代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.currentImageIndex = indexPath.item
        browser.imageCount = pictureInfoModelList?.count ?? 0
        
        browser.delegate = self
        browser.show()
    }
    
    
}



extension SinaHomePictureView: SDPhotoBrowserDelegate{
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let indexPath = IndexPath(item: index, section: 0)
        let cell = cellForItem(at: indexPath) as! SinaHomePictureViewCell
        let image = cell.imageV.image
        return image
    }
    
    
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = pictureInfoModelList![index].bmiddleURLStr ?? ""
        return URL(string: urlStr)
    }
}
